package com.kejiguan.ui;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;


import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.reflect.TypeToken;
import com.kejiguan.ui.adapter.DisplayMenuAdapter;
import com.kejiguan.ui.adapter.DisplayNeAdapterNew;
import com.kejiguan.ui.adapter.NeAdapter;
import com.kejiguan.ui.dialog.CommDialogUtil;
import com.kejiguan.ui.event.RefreshNeStateEvent;
import com.kejiguan.ui.model.DisplayArea;
import com.kejiguan.ui.model.ExhibitionNeItem;
import com.kejiguan.ui.presenter.DisplayFragmentPresenter;
import com.kejiguan.ui.response.GetNeItemInfosResponse;
import com.kejiguan.ui.response.TakeAllOffResponse;
import com.kejiguan.ui.util.CacheDataUtil;
import com.kejiguan.ui.util.CommonDate;
import com.kejiguan.ui.widget.NoScrollGridView;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.Iterator;
import java.util.List;
import java.util.Set;

/**
 * Created by apple on 16/3/2.
 *
 * 单个开关机
 */
public class DisplayFragmentNew extends Fragment implements View.OnClickListener {

    private View rootView;
    private RecyclerView displayMenuList;
    private NoScrollGridView displayItemList1;
    private NoScrollGridView displayItemList2;
    private View displayItemListDivider;
    private View dcTitleView,otherTitleView;

    private Button oneActionOnView,oneActionOffView,dcActionOnView,dcActionOffView;

    private int currentPosition = 0;
    private DisplayMenuAdapter menuAdapter;
    private DisplayNeAdapterNew neAdapterNew1;
    private DisplayNeAdapterNew neAdapterNew2;

    private DisplayFragmentPresenter mPresenter;
    private ExhibitionNeItem presenterItem;

    private Gson mGson;
    private DisplayArea yuliuArea;
    @Override
    public void onCreate(Bundle bundle) {
        super.onCreate(bundle);
        EventBus.getDefault().register(this);
        mPresenter = new DisplayFragmentPresenter();
        mPresenter.attach(getContext());
        yuliuArea=new DisplayArea();
        yuliuArea.setDisplayId("HY");
        yuliuArea.setDisplayName("预留上电操作");
        mGson = new GsonBuilder().excludeFieldsWithoutExposeAnnotation().enableComplexMapKeySerialization() //支持Map的key为复杂对象的形式
                .serializeNulls().setDateFormat("yyyy-MM-dd HH:mm:ss:SSS")//时间转化为特定格式
                .setPrettyPrinting() //对json结果格式化.
                .setVersion(1.0).create();
        List<ExhibitionNeItem> ps = mGson.fromJson(CommonDate.yuliu, new TypeToken<List<ExhibitionNeItem>>(){}.getType());
        yuliuArea.setExhibitionNeItems(ps);
    }

    @Override
    public final View onCreateView(LayoutInflater inflater, ViewGroup container,
                                   Bundle savedInstanceState) {

        if (rootView == null) {

            rootView = LayoutInflater.from(getContext()).inflate(R.layout.fragment_display_layout_new, container, false);
            displayMenuList = (RecyclerView) rootView.findViewById(R.id.display_menu_list);

            displayItemList1 = (NoScrollGridView) rootView.findViewById(R.id.ne_list1);
            displayItemList2 = (NoScrollGridView) rootView.findViewById(R.id.ne_list2);
            displayItemListDivider=rootView.findViewById(R.id.ne_list_divider);
            dcTitleView=rootView.findViewById(R.id.dc_title);
            otherTitleView=rootView.findViewById(R.id.other_title);

            oneActionOnView= (Button) rootView.findViewById(R.id.one_action_on_Img);
            oneActionOnView.setOnClickListener(this);
            oneActionOffView= (Button) rootView.findViewById(R.id.one_action_off_Img);
            oneActionOffView.setOnClickListener(this);
            dcActionOnView= (Button) rootView.findViewById(R.id.dc_action_on_Img);
            dcActionOnView.setOnClickListener(this);
            dcActionOffView= (Button) rootView.findViewById(R.id.dc_action_off_Img);
            dcActionOffView.setOnClickListener(this);

            LinearLayoutManager displayAreaLayoutManager = new LinearLayoutManager(getContext());
            displayAreaLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
            displayMenuList.setLayoutManager(displayAreaLayoutManager);
        }
        return rootView;
    }

    @Override
    public void onResume() {
        super.onResume();
        if (null == menuAdapter) {
            mPresenter.getNeItemInfos();
        } else {
            if (null != neAdapterNew1) {
                neAdapterNew1.notifyDataSetChanged();
            }
            if (null != neAdapterNew2) {
                neAdapterNew2.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

            case R.id.menu_name:
                ((MainActivity)getContext()).closeSlidingMenu();
                int position = (int) v.getTag(R.id.recyclerview_item_position);
                currentPosition = position;
                menuAdapter.setSelectArea(position);
                fillNeList();
                resetActionImageState();
                break;
            case R.id.displayitem_name:
                ((MainActivity)getContext()).closeSlidingMenu();
                presenterItem= (ExhibitionNeItem) v.getTag();
                if(null!=presenterItem)
                {
                    if(CommonDate.STATE_EXCEPTION.equals(presenterItem.getExhibitionState()))
                    {
                        SpannableString spanText = new SpannableString("关闭" + presenterItem.getExhibitionName() + "展项电源");
                        spanText.setSpan(new ForegroundColorSpan(Color.WHITE),2,presenterItem.getExhibitionName().length()+2, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        CommDialogUtil.getInstance().show(getContext(), spanText, DisplayFragmentNew.this, "断电", "取消", 2);
                    }else
                    {
                        boolean result1=!CommonDate.STATE_RUNNING.equals(presenterItem.getExhibitionState());
                        boolean result2=!CommonDate.STATE_EXIT.equals(presenterItem.getExhibitionState());
                        SpannableString spanText = new SpannableString("开启或关闭" + presenterItem.getExhibitionName() + "展项");
                        spanText.setSpan(new ForegroundColorSpan(Color.WHITE),5,presenterItem.getExhibitionName().length()+5, Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
                        CommDialogUtil.getInstance().show(getContext(), spanText, DisplayFragmentNew.this, "开机", "关机",true,true, 0);
                    }

                }
                break;
            case R.id.one_action_on_Img:
                CommDialogUtil.getInstance().show(getContext(), "开启" + menuAdapter.getSelectArea().getDisplayName() + "展区下所有展项", DisplayFragmentNew.this, "开启", "取消", 1);
                break;
            case R.id.one_action_off_Img:
                CommDialogUtil.getInstance().show(getContext(), "关闭" + menuAdapter.getSelectArea().getDisplayName() + "展区下所有展项", DisplayFragmentNew.this, "关机", "取消", 3);
                break;
            case R.id.dialog_confirm_btn:
                CommDialogUtil.getInstance().dismiss();
                int leftTag=(int) v.getTag(R.id.recyclerview_item_position);
                if (leftTag==0)//单个展项开启
                {
                    mPresenter.takeOn(presenterItem);

                }else if (leftTag==1)//展区下所有展项开启
                {
                    String exhibitionId=menuAdapter.getSelectArea().getDisplayId();
                    mPresenter.takeExhibitionOn(exhibitionId);
                }else if (leftTag==2)//单个展项断电
                {
                    mPresenter.poweroff(presenterItem);
                }else if (leftTag==3)//展区下所有展项关闭
                {
                    String exhibitionId=menuAdapter.getSelectArea().getDisplayId();
                    mPresenter.takeExceptionOff(exhibitionId);
                }
                else if (leftTag==6)//大仓展项下开机
                {
                    mPresenter.takeDCOn();
                }
                else if (leftTag==7)//大仓展项下关机
                {
                    mPresenter.takeDCOff();
                }
                break;
            case R.id.dialog_cancel_btn:
                CommDialogUtil.getInstance().dismiss();
                int rightTag=(int) v.getTag(R.id.recyclerview_item_position);
                if (rightTag==0)//单个展项关闭
                {
                    mPresenter.takeOff(presenterItem);
                }
                break;
            case R.id.dialog_one_btn:
                CommDialogUtil.getInstance().dismissOne();
                break;
            case R.id.dc_action_on_Img://大仓开机
                CommDialogUtil.getInstance().show(getContext(), "开启神州与天宫下所有展项", DisplayFragmentNew.this, "开机", "取消", 6);
                break;
            case R.id.dc_action_off_Img://大仓关机
                CommDialogUtil.getInstance().show(getContext(), "关闭神州与天宫下所有展项", DisplayFragmentNew.this, "关机", "取消", 7);
                break;
        }


    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(GetNeItemInfosResponse response) {
        if ("0000".equals(response.getRetCode()) && !response.getExhibitionRecordMap().isEmpty()) {
            menuAdapter = new DisplayMenuAdapter(getContext(), CacheDataUtil.getInstance().getDisplayAreas());
            menuAdapter.setYuliuArea(yuliuArea);
            menuAdapter.setOnClickListener(this);
            displayMenuList.setAdapter(menuAdapter);
            fillNeList();
            EventBus.getDefault().post(new RefreshNeStateEvent());
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(RefreshNeStateEvent event) {
        menuAdapter.notifyDataSetChanged();
        fillNeList();
        resetActionImageState();
    }


    private void fillNeList()
    {
        if ("H004".equals(menuAdapter.getDisplayAreaByPosition(currentPosition).getDisplayId()))
        {
            if (neAdapterNew1==null)
            {
                neAdapterNew1=new DisplayNeAdapterNew(getContext(),menuAdapter.getDisplayAreaByPosition(currentPosition).getDcExhibitionNeItems());
                neAdapterNew1.setOnClickListener(DisplayFragmentNew.this);
                displayItemList1.setAdapter(neAdapterNew1);
            }else
            {
                neAdapterNew1.setPresenterItems(menuAdapter.getDisplayAreaByPosition(currentPosition).getDcExhibitionNeItems());
            }

            displayItemList1.setVisibility(View.VISIBLE);
            displayItemListDivider.setVisibility(View.VISIBLE);
            dcTitleView.setVisibility(View.VISIBLE);
            otherTitleView.setVisibility(View.VISIBLE);

            if (neAdapterNew2==null)
            {
                neAdapterNew2=new DisplayNeAdapterNew(getContext(),menuAdapter.getDisplayAreaByPosition(currentPosition).getNomalExhibitionNeItems());
                neAdapterNew2.setOnClickListener(DisplayFragmentNew.this);
                displayItemList2.setAdapter(neAdapterNew2);
            }else
            {
                neAdapterNew2.setPresenterItems(menuAdapter.getDisplayAreaByPosition(currentPosition).getNomalExhibitionNeItems());
            }

        }else
        {
            displayItemList1.setVisibility(View.GONE);
            displayItemListDivider.setVisibility(View.GONE);
            dcTitleView.setVisibility(View.GONE);
            otherTitleView.setVisibility(View.GONE);
            if (neAdapterNew2==null)
            {
                neAdapterNew2=new DisplayNeAdapterNew(getContext(),menuAdapter.getDisplayAreaByPosition(currentPosition).getExhibitionNeItems());
                neAdapterNew2.setOnClickListener(DisplayFragmentNew.this);
                displayItemList2.setAdapter(neAdapterNew2);
            }else
            {
                neAdapterNew2.setPresenterItems(menuAdapter.getDisplayAreaByPosition(currentPosition).getExhibitionNeItems());
            }

            displayItemList2.setVisibility(View.VISIBLE);
        }

    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onEventMainThread(TakeAllOffResponse response) {

        if (!response.getRetCode().equals("0000"))
        {
            CommDialogUtil.getInstance().showOne(getContext(),response.getRetInfo(),DisplayFragmentNew.this,"确定",0);
        }
    }



    private void resetActionImageState()
    {

        if (null!=menuAdapter&&null!=menuAdapter.getSelectArea()&&"H004".equals(menuAdapter.getSelectArea().getDisplayId()))
        {

            dcActionOffView.setVisibility(View.VISIBLE);
            dcActionOnView.setVisibility(View.VISIBLE);
        }else
        {
            dcActionOffView.setVisibility(View.GONE);
            dcActionOnView.setVisibility(View.GONE);
        }

        if (null!=menuAdapter&&null!=menuAdapter.getSelectArea()&&"HY".equals(menuAdapter.getSelectArea().getDisplayId()))
        {
            oneActionOnView.setVisibility(View.GONE);
            oneActionOffView.setVisibility(View.GONE);
        }else
        {
            oneActionOnView.setVisibility(View.VISIBLE);
            oneActionOffView.setVisibility(View.VISIBLE);
        }

        boolean isAllOn=true;
        boolean isAllOff=true;

        List<ExhibitionNeItem> exhibitionNeItems=menuAdapter.getDisplayAreaByPosition(currentPosition).getExhibitionNeItems();
        for (ExhibitionNeItem exhibitionNeItem:exhibitionNeItems)
        {
            if (!CommonDate.STATE_RUNNING.equals(exhibitionNeItem.getExhibitionState()))
            {
                isAllOn=false;
                break;
            }
        }

        for (ExhibitionNeItem exhibitionNeItem:exhibitionNeItems)
        {
            if (!CommonDate.STATE_EXIT.equals(exhibitionNeItem.getExhibitionState()))
            {
                isAllOff=false;
                break;
            }
        }


        if (isAllOn)
        {
            oneActionOnView.setClickable(false);
            oneActionOnView.setBackgroundResource(R.mipmap.kjg_take_on_btn_bg2);
        }else
        {
            oneActionOnView.setClickable(true);
            oneActionOnView.setBackgroundResource(R.mipmap.kjg_take_on_btn_bg);
        }

        if (isAllOff)
        {
            oneActionOffView.setClickable(false);
            oneActionOffView.setBackgroundResource(R.mipmap.kjg_take_off_btn_bg2);
        }else
        {
            oneActionOffView.setClickable(true);
            oneActionOffView.setBackgroundResource(R.mipmap.kjg_take_off_btn_bg);
        }
    }



}
